package com.xu.mb3.jdk;

import com.xu.mybatis.constant.MblConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 原生jdk获取数据库连接
 *
 * @author xuguan
 * @since 2024/11/9
 */
@Slf4j
public class DbUtil {
    /**
     * 连接数据库
     */
    public static Connection connect() {

        try {
            // 读取数据库配置文件
            Properties prop = new Properties();
            prop.load(Resources.getResourceAsStream(MblConstant.JDBC_PROPERTIES_NAME));

            // 加载mysql驱动
            Class.forName(MblConstant.MYSQL8_DRIVER_CLASS_NAME);

            String url = prop.getProperty(MblConstant.JDBC_URL_NAME);
            String username = prop.getProperty(MblConstant.JDBC_USERNAME_NAME);
            String password = prop.getProperty(MblConstant.JDBC_PASSWORD_NAME);

            // 连接数据库
            return DriverManager.getConnection(url, username, password);
        } catch (IOException e) {
            log.error("读取数据源配置文件失败", e);
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            log.error("数据库驱动加载失败, 未找到数据库驱动", e);
            throw new RuntimeException(e);
        } catch (SQLException e) {
            log.error("获取数据库连接失败", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭数据库连接
     *
     * @param connection 关闭的连接对象
     * @param statement  关闭的语句对象
     * @param resultSet  关闭的结果集对象
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            log.info("关闭数据库连接失败", e);
            throw new RuntimeException(e);
        }
    }

}
